//
//  SSEmoticon.swift
//  表情包数据
//
//  Created by 叶竞泽 on 2017/2/3.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit
import YYModel

class SSEmoticon: NSObject {
    
    /// 表情类型 false - 图片表情 / true - emoji
    var type = false
    
    /// 表情字符串 - 发送给新浪微博服务器,节约流量
    var chs: String?
    
    /// 表情名称 - 用户本地图文混排
    var png: String?
    
    /// emoji的十六进制编码
    var code: String? {
        
        didSet {
            
            guard let code = code else { return }
            
            var result: UInt32 = 0
            Scanner(string: code).scanHexInt32(&result)
            
            emoji = String(Character(UnicodeScalar(result)!))
        }
    }
    
    /// emoji字符串
    var emoji: String?
    
    /// 表情模型所在的目录
    var directory: String?
    
    /// 图片表情对应的图像
    var image: UIImage?  {
        
        // 判断表情类型,如果是emoji,就直接返回nil
        if type {
            return nil
        }
        
        guard let png = png, let directory = directory, let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil), let bundle = Bundle(path: path) else {
            return nil
        }
        
        return UIImage(named: "\(directory)/\(png)", in: bundle, compatibleWith: nil)
    }
    
    /// 行高
    var lineHeight: CGFloat?
    
    /// 表情使用次数
    var times: Int = 0
    
    /// 重写类描述
    override var description: String {
        return yy_modelDescription()
    }
    
    /// 将当前的表情字符串转换为属性字符串
    ///
    /// - Returns: 属性字符串
    func imageText(font: UIFont) -> NSAttributedString {
        
        // 1.判断图像是否存在
        guard let image = image else {
            return NSAttributedString(string: "")
        }

        let attachment = SSEmoticonAttachment()
        attachment.image = image
        attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
        
        // 记录属性的纯文本
        attachment.chs = chs
        
        let attrM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        attrM.addAttributes([NSFontAttributeName: font], range: NSRange(location: 0, length: attrM.length))
        return attrM
        
    }
    
}
